package cn.eric.framework.exception.utils;

import cn.eric.framework.exception.domain.EExceCfg;
import cn.eric.framework.exception.domain.exception.BusinessException;
import cn.eric.framework.log.log4j2.Log4Framework;
import cn.eric.framework.utils.CfgUtil;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;

import javax.annotation.Resource;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.net.URISyntaxException;

@Component
public class EExceptionUtil {
    private static final String LOG_TITLE = "EException";
    @Resource
    private Logger logger;

    public void initEException(String path) throws IllegalAccessException, JAXBException, InstantiationException, IOException {

        logger.info(Log4Framework.create(LOG_TITLE, "开始验证配置文件正确性。"));
        try {
            if (CfgUtil.validateXMLWithSchema(EExceptionConstant.EEXCEPTION_CFG_XSD_PATH, path)) {
                logger.info(Log4Framework.create(LOG_TITLE, "配置文件正确。"));

                logger.info(Log4Framework.create(LOG_TITLE, "解析业务异常列表。"));
                EExceCfg eExceCfg = CfgUtil.JAXBParser(EExceCfg.class, path);
                // 构建业务异常Map
                EExceptionMap.init(eExceCfg.getBusinessExceptions());

                for (BusinessException be : EExceptionMap.idBusinessExceptionMap.values()) {
                    logger.info(Log4Framework.create(LOG_TITLE, be.toString()));
                }
                logger.info(Log4Framework.create(LOG_TITLE, "解析业务异常列表成功。"));
            }
        } catch (URISyntaxException | SAXException e) {
            logger.fatal(Log4Framework.create(LOG_TITLE, "配置文件验证失败。", e.getMessage()));
        }
    }
}
